package org.hyacinth.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.hyacinth.blog.api.BlogServiceApi;
import org.hyacinth.blog.api.pojo.response.BlogInfoResponse;
import org.hyacinth.common.constant.Constants;
import org.hyacinth.common.exception.BlogException;
import org.hyacinth.common.pojo.Result;
import org.hyacinth.common.utils.*;
import org.hyacinth.user.api.pojo.request.UserInfoRegisterReq;
import org.hyacinth.user.api.pojo.request.UserInfoRequest;
import org.hyacinth.user.api.pojo.response.UserInfoResponse;
import org.hyacinth.user.api.pojo.response.UserLoginResponse;
import org.hyacinth.user.dataobject.UserInfo;
import org.hyacinth.user.mapper.UserInfoMapper;
import org.hyacinth.user.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Resource
    private BlogServiceApi blogServiceApi;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
        boolean exits = redisUtils.hasKey(user.getUserName());
        UserInfo userInfo = null;
        if (!exits) {
            userInfo = selectUserInfoByName(user.getUserName());
            redisUtils.set(redisUtils.buildKey(userInfo.getUserName()), JsonUtils.toJson(userInfo), 14, TimeUnit.DAYS);
        } else {
            userInfo = JsonUtils.parseJson(redisUtils.get(redisUtils.buildKey(user.getUserName())), UserInfo.class);
            log.info("从redis中获取userInfo: " + userInfo);
        }
        if (userInfo == null || userInfo.getId() == null) {
            throw new BlogException("用户不存在");
        }
//        if (!user.getPassword().equals(userInfo.getPassword())) {
//            throw new BlogException("用户密码不正确");
//        }
        if (!SecurityUtil.verify(user.getPassword(), userInfo.getPassword())) {
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //1. 根据博客ID, 获取作者ID
        Result<BlogInfoResponse> blogInfoResponseResult = blogServiceApi.getBlogDeatail(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogInfoResponseResult == null || blogInfoResponseResult.getData() == null) {
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogInfoResponseResult.getData().getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public Integer register(UserInfoRegisterReq userInfoRegisterReq) {
        if (!RegexUtil.checkMail(userInfoRegisterReq.getEmail())) {
            throw new BlogException("邮箱格式错误！");
        }
        if (!RegexUtil.checkURL(userInfoRegisterReq.getGithubUrl())) {
            throw new BlogException("github url格式错误！");
        }
        UserInfo existUserInfo = selectUserInfoByName(userInfoRegisterReq.getUserName());
        if (existUserInfo != null) {
            throw new BlogException("用户名重复！");
        }
        userInfoRegisterReq.setPassword(SecurityUtil.encrypt(userInfoRegisterReq.getPassword()));
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoRegisterReq, userInfo);
        Integer ret = userInfoMapper.insert(userInfo);
        if (ret == 0) {
            throw new BlogException("用户注册失败！");
        }
        redisUtils.set(redisUtils.buildKey(userInfo.getUserName()), JsonUtils.toJson(userInfo), 14, TimeUnit.DAYS);
        userInfo.setPassword(null);
        rabbitTemplate.convertAndSend(Constants.USER_EXCHANGE_NAME, "", JsonUtils.toJson(userInfo));
        return userInfo.getId();
    }

    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }

    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }
}
